package dao;

import common.Topic;
import service.FlushCourse;

import java.sql.*;

public class PublishWork {
    private static Connection conn=DataBaseConnect.getConn();
    private static String sql="INSERT INTO assignment (courseid,title,createdate,deaddate,createtime,deadtime) VALUES(?,?,?,?,?,?)";
    private static String sql2="INSERT INTO topic (assignmentid,content) VALUES(?,?)";
    private static PreparedStatement pstmt;
    private static PreparedStatement pstmt2;
    static {
        try {
            pstmt=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            pstmt2=conn.prepareStatement(sql2);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void publishWork(Topic topic){
        try {
            pstmt.setString(1,topic.getCourse().getId());
            pstmt.setString(2,topic.getTitle());
            pstmt.setString(3,topic.getPulishdate());
            pstmt.setString(4, topic.getDeaddate());
            pstmt.setString(5, topic.getPulishtime());
            pstmt.setString(6, topic.getDeadtime());
            int count=pstmt.executeUpdate();
            if(count==1){
                ResultSet rs=pstmt.getGeneratedKeys();
                while (rs.next()){
                    pstmt2.setString(1, rs.getString(1));
                    for(int i=0;i<topic.getQuestion().size();i++){
                        pstmt2.setString(2, topic.getQuestion().get(i));
                        pstmt2.executeUpdate();
                    }
                }
                for(int i=0;i<topic.getCourse().getStudent().size();i++){
                    FlushCourse.flush(topic.getCourse().getStudent().get(i).getId());
                }
            }
        } catch (SQLException e) {
            System.out.println("发布作业失败");;
        }
    }
}

